package cn.supermarket.utils;

import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Component
public class PasswordEncoder {

    public String encode(String rawPassword) {
        String salt = UUID.randomUUID().toString().replace("-", "");
        String encodedPassword = rawPassword;
        System.out.println("rawPassword0: "+rawPassword);
        for (int i = 0; i < 5; i++) {
            encodedPassword = DigestUtils.md5DigestAsHex(
                    (salt + encodedPassword + salt + encodedPassword + salt).getBytes());
        }
        return salt + encodedPassword;
    }

    public boolean matches(String rawPassword, String encodedPassword) {
        String salt = encodedPassword.substring(0, 32);
        System.out.println("salt: " + salt);
        String newPassword = rawPassword;
        System.out.println("rawPassword: "+rawPassword);
        for (int i = 0; i < 5; i++) {
            newPassword = DigestUtils.md5DigestAsHex(
                    (salt + newPassword + salt + newPassword + salt).getBytes());
        }
        System.out.println("newPassword1: "+newPassword);
        newPassword = salt + newPassword;
        System.out.println("newPassword2: "+newPassword);
        return newPassword.equals(encodedPassword);
    }
}







